<!-- 健康记录组件 -->
<template>
  <div class="health-record">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>健康数据记录</span>
          <el-button type="primary" @click="showAddDialog">添加记录</el-button>
        </div>
      </template>

      <!-- 数据统计卡片 -->
      <div class="stat-cards" v-if="latestRecord">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-card shadow="hover">
              <template #header>
                <div class="stat-header">
                  <i class="el-icon-data-line"></i>
                  血压 (mmHg)
                </div>
              </template>
              <div class="stat-value">{{ latestRecord.bloodPressure || '暂无数据' }}</div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card shadow="hover">
              <template #header>
                <div class="stat-header">
                  <i class="el-icon-data-line"></i>
                  心率 (次/分)
                </div>
              </template>
              <div class="stat-value">{{ latestRecord.heartRate || '暂无数据' }}</div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card shadow="hover">
              <template #header>
                <div class="stat-header">
                  <i class="el-icon-data-line"></i>
                  体重 (kg)
                </div>
              </template>
              <div class="stat-value">{{ latestRecord.weight || '暂无数据' }}</div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 图表展示 -->
      <div class="charts">
        <el-tabs v-model="activeChart">
          <el-tab-pane label="血压趋势" name="bloodPressure">
            <div class="chart-container">
              <v-chart :option="bloodPressureChartOption" autoresize />
            </div>
          </el-tab-pane>
          <el-tab-pane label="心率趋势" name="heartRate">
            <div class="chart-container">
              <v-chart :option="heartRateChartOption" autoresize />
            </div>
          </el-tab-pane>
          <el-tab-pane label="体重趋势" name="weight">
            <div class="chart-container">
              <v-chart :option="weightChartOption" autoresize />
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 记录列表 -->
      <div class="record-list">
        <el-table :data="records" stripe style="width: 100%">
          <el-table-column prop="recordDate" label="日期" width="120" />
          <el-table-column prop="bloodPressure" label="血压" width="120" />
          <el-table-column prop="heartRate" label="心率" width="100" />
          <el-table-column prop="bloodSugar" label="血糖" width="100" />
          <el-table-column prop="weight" label="体重" width="100" />
          <el-table-column prop="temperature" label="体温" width="100" />
          <el-table-column prop="sleepHours" label="睡眠时长" width="100" />
          <el-table-column prop="exerciseMinutes" label="运动时长" width="100" />
          <el-table-column prop="note" label="备注" />
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 添加/编辑记录对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加健康记录' : '编辑健康记录'"
      width="50%"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="记录日期" prop="recordDate">
          <el-date-picker
            v-model="form.recordDate"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="血压" prop="bloodPressure">
          <el-input v-model="form.bloodPressure" placeholder="例如: 120/80" />
        </el-form-item>
        <el-form-item label="心率" prop="heartRate">
          <el-input-number v-model="form.heartRate" :min="0" :max="200" />
        </el-form-item>
        <el-form-item label="血糖" prop="bloodSugar">
          <el-input-number v-model="form.bloodSugar" :min="0" :max="30" :precision="1" :step="0.1" />
        </el-form-item>
        <el-form-item label="体重" prop="weight">
          <el-input-number v-model="form.weight" :min="0" :max="300" :precision="1" :step="0.1" />
        </el-form-item>
        <el-form-item label="体温" prop="temperature">
          <el-input-number v-model="form.temperature" :min="35" :max="42" :precision="1" :step="0.1" />
        </el-form-item>
        <el-form-item label="睡眠时长" prop="sleepHours">
          <el-input-number v-model="form.sleepHours" :min="0" :max="24" :precision="1" :step="0.5" />
        </el-form-item>
        <el-form-item label="运动时长" prop="exerciseMinutes">
          <el-input-number v-model="form.exerciseMinutes" :min="0" :max="1440" />
        </el-form-item>
        <el-form-item label="备注" prop="note">
          <el-input
            v-model="form.note"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'

use([
  CanvasRenderer,
  LineChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

const records = ref([])
const latestRecord = ref(null)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const dialogType = ref('add')
const activeChart = ref('bloodPressure')
const formRef = ref(null)

const form = ref({
  recordDate: new Date(),
  bloodPressure: '',
  heartRate: null,
  bloodSugar: null,
  weight: null,
  temperature: null,
  sleepHours: null,
  exerciseMinutes: null,
  note: ''
})

const rules = {
  recordDate: [{ required: true, message: '请选择记录日期', trigger: 'change' }]
}

// 获取记录列表
const loadRecords = async () => {
  try {
    const userId = JSON.parse(sessionStorage.getItem('user')).id
    const response = await axios.get('/health/records', {
      params: {
        userId,
        pageNum: currentPage.value,
        pageSize: pageSize.value
      }
    })
    if (response.data.code === 200) {
      records.value = response.data.result.records
      total.value = response.data.result.total
    }
  } catch (error) {
    console.error('加载记录失败:', error)
    ElMessage.error('加载记录失败')
  }
}

// 获取最新记录
const loadLatestRecord = async () => {
  try {
    const userId = JSON.parse(sessionStorage.getItem('user')).id
    const response = await axios.get('/health/record/latest', {
      params: { userId }
    })
    if (response.data.code === 200) {
      latestRecord.value = response.data.result
    }
  } catch (error) {
    console.error('加载最新记录失败:', error)
  }
}

// 加载图表数据
const loadChartData = async () => {
  try {
    const userId = JSON.parse(sessionStorage.getItem('user')).id
    const endDate = new Date()
    const startDate = new Date()
    startDate.setDate(startDate.getDate() - 30)
    
    const response = await axios.get('/health/records/range', {
      params: {
        userId,
        startDate: startDate.toISOString().split('T')[0],
        endDate: endDate.toISOString().split('T')[0]
      }
    })
    
    if (response.data.code === 200) {
      const data = response.data.result
      updateChartOptions(data)
    }
  } catch (error) {
    console.error('加载图表数据失败:', error)
  }
}

// 更新图表配置
const updateChartOptions = (data) => {
  const dates = data.map(item => item.recordDate)
  
  // 血压图表配置
  bloodPressureChartOption.value = {
    title: { text: '血压趋势' },
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: dates },
    yAxis: { type: 'value', name: 'mmHg' },
    series: [{
      name: '收缩压',
      type: 'line',
      data: data.map(item => item.bloodPressure ? parseInt(item.bloodPressure.split('/')[0]) : null)
    }, {
      name: '舒张压',
      type: 'line',
      data: data.map(item => item.bloodPressure ? parseInt(item.bloodPressure.split('/')[1]) : null)
    }]
  }
  
  // 心率图表配置
  heartRateChartOption.value = {
    title: { text: '心率趋势' },
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: dates },
    yAxis: { type: 'value', name: '次/分' },
    series: [{
      name: '心率',
      type: 'line',
      data: data.map(item => item.heartRate)
    }]
  }
  
  // 体重图表配置
  weightChartOption.value = {
    title: { text: '体重趋势' },
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: dates },
    yAxis: { type: 'value', name: 'kg' },
    series: [{
      name: '体重',
      type: 'line',
      data: data.map(item => item.weight)
    }]
  }
}

// 图表配置
const bloodPressureChartOption = ref({})
const heartRateChartOption = ref({})
const weightChartOption = ref({})

// 显示添加对话框
const showAddDialog = () => {
  dialogType.value = 'add'
  form.value = {
    recordDate: new Date(),
    bloodPressure: '',
    heartRate: null,
    bloodSugar: null,
    weight: null,
    temperature: null,
    sleepHours: null,
    exerciseMinutes: null,
    note: ''
  }
  dialogVisible.value = true
}

// 编辑记录
const handleEdit = (row) => {
  dialogType.value = 'edit'
  form.value = { ...row }
  dialogVisible.value = true
}

// 删除记录
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
      type: 'warning'
    })
    
    const userId = JSON.parse(sessionStorage.getItem('user')).id
    const response = await axios.delete('/health/record', {
      params: {
        recordId: row.id,
        userId
      }
    })
    
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      loadRecords()
      loadLatestRecord()
      loadChartData()
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    const userId = JSON.parse(sessionStorage.getItem('user')).id
    const data = {
      ...form.value,
      userId
    }
    
    const url = '/health/record'
    const method = dialogType.value === 'add' ? 'post' : 'put'
    
    const response = await axios[method](url, data)
    
    if (response.data.code === 200) {
      ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
      dialogVisible.value = false
      loadRecords()
      loadLatestRecord()
      loadChartData()
    } else {
      ElMessage.error(response.data.message || (dialogType.value === 'add' ? '添加失败' : '更新失败'))
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  loadRecords()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadRecords()
}

onMounted(() => {
  loadRecords()
  loadLatestRecord()
  loadChartData()
})
</script>

<style scoped>
.health-record {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  color: #409EFF;
}

.charts {
  margin: 20px 0;
}

.chart-container {
  height: 400px;
}

.record-list {
  margin-top: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-input-number) {
  width: 100%;
}
</style> 